#include "app_message.h"


/**
 * @brief 把字节数组转换为json
 */
char *app_message_charToJson(uint8_t *data, int data_len)
{
    //  把字节数组的提取为变量
    // 01 00 00 61 45 01 00  -> {"device_id ": 1 ,"motor_status":"on" ,"cur_angle":3600}
    uint8_t device_id = data[0];
    float cur_angle =0.0;
    memcpy(&cur_angle, data+1, 4);
    char *motor_status = data[5] == 0 ? "off" : "on";
    // 把变量写入cjson结构体
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "device_id", device_id);
    cJSON_AddStringToObject(root, "motor_status", motor_status);
    char cur_angle_str[9]; 
    sprintf(cur_angle_str, "%8.1f", cur_angle);
    cJSON_AddStringToObject(root, "cur_angle", cur_angle_str);

    // 转换为json字符串
    char *json = cJSON_PrintUnformatted(root);

    // 释放cjson结构体
    cJSON_Delete(root);
    
    //  发送完mqtt后 释放json字符串
    // cJSON_free(json);

    return json;



}


/**
 * @brief 把json转换为字节数组
 * @return 转换后的字节数
 */
int app_message_jsonToChar(char *json, uint8_t *buff, int buff_len)
{
    // 从json中提取变量    {"device_id ": 1 ,"target_angle":3600 ,"max_speed":60}
    cJSON *root = cJSON_Parse(json);
    cJSON *device_id_cjson = cJSON_GetObjectItem(root, "device_id");
    cJSON *target_angle_cjson = cJSON_GetObjectItem(root, "target_angle");
    cJSON *max_speed_cjson = cJSON_GetObjectItem(root, "max_speed");
    uint8_t device_id = device_id_cjson->valueint;
    float target_angle =(float) target_angle_cjson->valuedouble;
    float max_speed =(float) max_speed_cjson->valuedouble;


    // 把变量拼接为字节数组
     if(buff_len < 9)
     {
         log_error("buff_len < 9  not enough");
         return -1;
     }
     buff[0] = device_id;
     memcpy(buff+1, &target_angle, 4);  
     memcpy(buff+5, &max_speed, 4);  


     return 9;


}